import request from '@/utils/request';
import { message, TreeSelect } from 'antd';
import { useEffect, useState } from 'react';

const GroupTreeSelect = (props) => {
  const { style, value, onChange, ...rest } = props;

  const [treeData, setTreeData] = useState([]);

  useEffect(() => {
    const fetchGroup = async () => {
      try {
        const data = await request({
          url: '/base/group/list',
          method: 'get',
          params: {
            index: 0,
            size: 0,
          },
        });
        const newdata = data.map((item) => {
          return {
            ...item,
            pId: item.groupFid,
            id: item.groupId,
          };
        });
        setTreeData(newdata);
      } catch (error) {
        console.error('获取组织数据失败:', error);
        message.error('获取组织数据失败');
      }
    };

    fetchGroup();
  }, []);

  const onChangeHandle = (_value) => {
    if (onChange) {
      onChange(_value);
    }
  };

  return (
    <TreeSelect
      showSearch
      value={value}
      style={{ ...style }}
      treeData={treeData}
      treeDataSimpleMode={true}
      fieldNames={{ label: 'groupName', value: 'groupId' }}
      placeholder="请选择组织"
      onChange={onChangeHandle}
      treeNodeFilterProp="groupName"
      allowClear
      {...rest}
    />
  );
};

export default GroupTreeSelect;
